using Cysharp.Threading.Tasks;
using GameFramework;
using GameFramework.Configuration;
using GameFramework.Event;
using GameFramework.Fsm;
using GameFramework.Procedure.Attribute;
using GameFramework.Procedure.Fsm;
using GameLogic.Login;

namespace GameLogic.Launch
{
    /// <summary>
    /// 加载配置表流程
    /// </summary>
    [Procedure]
    public sealed class LoadConfigProcedure : AFsmProcedure
    {
        private bool m_LoadComplete;

        public override void OnEnter(IFsm fsm)
        {
            base.OnEnter(fsm);
            m_LoadComplete = false;
            EventService.That.Raise(this, LaunchStepUpdatedEvent.Acquire(LaunchStep.LoadConfig));
            LoadConfigAsync().Forget();
        }

        public override void OnUpdate(IFsm fsm, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(fsm, elapseSeconds, realElapseSeconds);

            if (!m_LoadComplete)
                return;

            Change<LoginProcedure>(fsm);
        }

        private async UniTask LoadConfigAsync()
        {
            var code = await ConfigurationService.That.LoadAsync();
            if (code != 0)
            {
                Log.Error($"Load config failed, code: {code}");
                return;
            }

            m_LoadComplete = true;
            EventService.That.Raise(this, LaunchStepUpdatedEvent.Acquire(LaunchStep.LoadConfig, 1f));
        }
    }
}